package com.yff.tuan.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yff.tuan.mapper.ClabelMapper;
import com.yff.tuan.mapper.ClabelTypeMapper;
import com.yff.tuan.model.Clabel;
import com.yff.tuan.model.ClabelExample;
import com.yff.tuan.model.ClabelType;
import com.yff.tuan.model.ClabelTypeExample;
import com.yff.tuan.service.LabelService;

@Component
public class LabelServiceImpl implements LabelService {
	@Autowired
	ClabelMapper clabelMapper;
	@Autowired
	ClabelTypeMapper clabelTypeMapper;
	

	@Override
	public List<Clabel> query(ClabelExample example) {
		return clabelMapper.selectByExample(example);
	}


	@Override
	public Clabel find(Integer id) {
		Clabel clabel = clabelMapper.selectByPrimaryKey(id);
		if(null != clabel) {
			ClabelTypeExample example = new ClabelTypeExample();
			example.createCriteria().andLabelIdEqualTo(clabel.getId());
			List<ClabelType> clabelTypes = clabelTypeMapper.selectByExample(example);
			clabel.setClabelTypes(clabelTypes);
		}
		return clabel;
	}


	@Override
	public List<ClabelType> queryClabelType(Integer labelId) {
		ClabelTypeExample example = new ClabelTypeExample();
		example.createCriteria().andLabelIdEqualTo(labelId);
		return clabelTypeMapper.selectByExample(example);
	}


	@Override
	public boolean add(Clabel clabel) {
		int id = clabelMapper.insert(clabel);
		List<ClabelType> clabelTypes = clabel.getcAdd();
		if(null != clabelTypes && !clabelTypes.isEmpty()) {
			for(ClabelType clabelType:clabelTypes) {
				clabelType.setLabelId(clabel.getId());
				clabelTypeMapper.insert(clabelType);
			}
		}
		return id>0?true:false;
	}


	@Override
	public boolean update(Clabel clabel) {
		int id = clabelMapper.updateByPrimaryKey(clabel);
		List<ClabelType> clabelTypeAdd = clabel.getcAdd();
		List<ClabelType> clabelTypeUpdate = clabel.getcUpdate();
		if(null != clabelTypeAdd && !clabelTypeAdd.isEmpty()) {
			for(ClabelType clabelType:clabelTypeAdd) {
				clabelType.setLabelId(clabel.getId());
				clabelTypeMapper.insert(clabelType);
			}
		}
		if(null != clabelTypeUpdate && !clabelTypeUpdate.isEmpty()) {
			for(ClabelType clabelType:clabelTypeUpdate) {
				clabelTypeMapper.updateByPrimaryKey(clabelType);
			}
		}
		return id>0?true:false;
	}

}
